<?php
namespace app\admin\controller\app;


use app\common\controller\AdminController;
use think\app;
use think\facade\View;

class Apps extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = app('app\common\model\app\App');
        $this->authmodel = app('app\common\model\system\SystemAuth');
        $this->adminmodel = app('app\common\model\system\SystemAdmin');
    }

    public function get_other(){
        $data = $this->authmodel->select();

        View::assign('auth',$data);
    }

    public function get_where($arr = []){
        $array = [];
        if(!empty($arr['name']) && isset($arr['name'])){
            $array[] = ['name','like','%'.$arr['name'].'%'];
        }
        return $array;
    }

    /**
     * 获取验证规则
     * @param $post
     * @return array
     */
    public function get_check_rule($post)
    {
        $rule = [
            'name|项目名称'   => 'unique:app,name,'.$post['id'].',id',
            'username|超级管理员账号'  => 'unique:system_admin,username,'.$post['id'].',id',
        ];

        return $rule;
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $row = $this->model->find($id);


        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            try {
                $post = $this->request->post();
                $rule = [];
                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }
                $this->validate($post, $rule);

                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error($e->getMessage());
        }
        $row['admin'] = $this->adminmodel->field('username,password,auth_ids')->where(['app_id'=>$row['id'],'is_super'=>1])->find();
        if(method_exists($this,'get_other')){
            $this->get_other($this->request->param() ?? []);
        }
        return view('', compact('row'));
    }

}